package com.beta.restapi.controller;

import com.beta.common.exception.ControllerException;
import com.beta.common.web.ContentType;
import com.beta.constant.CommonConstant;
import com.beta.restapi.internal.Consts;
import com.beta.service.IPaymentsService;
import com.beta.vo.payment.PaymentVO;
import com.beta.dto.pay.PaymentDto;
import com.beta.em.pay.PayRoutes;
import com.beta.restapi.request.order.OrderPayRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.Optional;

/**
 * Created by vector on 2016/11/24.
 */
@Api(tags = Consts.Resource.PAYMENTS)
@RestController
@RequestMapping(Consts.API_PATH_PREFIX + Consts.Resource.PAYMENTS)
public class PaymentController extends BaseController {

    @Autowired
    private IPaymentsService paymentsService;

    @ApiOperation("订单支付")
    @ApiResponses({
            @ApiResponse(code = 200, message = "Success", response = PaymentVO.class)
    })
    @PostMapping(value = "", consumes = {ContentType.JSON}, produces = {ContentType.JSON})
    public Object payOrder(@RequestHeader(Consts.HEADER_AUTH_KEY) String token,
                           @RequestBody OrderPayRequest payRequest) {
        Integer orderId = payRequest.getOrderId();
        String clientIp = getClientIp();
        PayRoutes payRoutes = PayRoutes.getPayRoutes(payRequest.getPayRoute());
        if (Objects.isNull(payRoutes)) {
            throw new ControllerException("E60002", payRequest.getPayRoute());
        }

        PaymentDto payResult = paymentsService.executePayOrder(getCurrentUserId(), orderId, payRoutes, clientIp);
        PaymentVO paymentVO = Optional.of(payResult).map(payment -> {
            PaymentVO paymentVOTmp = new PaymentVO();
            paymentVOTmp.setPayUrl(payment.getPayUrl());
            paymentVOTmp.setAmount(payment.getAmount().setScale(2, CommonConstant.ROUNDING_MODE).toString()); //使用银行家算法
            return paymentVOTmp;
        }).orElse(null);
        return ok(paymentVO);
    }
}
